﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Soft
{

    /// <summary>
    /// 转换为T对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class StructObjectTypeConverter<T> : ExpandableObjectConverter where T : struct
    {
        public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
        {
            return true;
        }

        public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
        {
            if (propertyValues == null)
            {
                throw new ArgumentNullException("propertyValues");
            }
            T t = default(T);
            object obj = t;
            foreach (object obj2 in propertyValues)
            {
                DictionaryEntry dictionaryEntry = (DictionaryEntry)obj2;
                PropertyInfo property = t.GetType().GetProperty(dictionaryEntry.Key.ToString());
                if (property != null && property.CanWrite)
                {
                    property.SetValue(obj, Convert.ChangeType(dictionaryEntry.Value, property.PropertyType), null);
                }
            }
            return (T)((object)obj);
        }

    }
}
